package com.roc.producer.messageType;

import com.roc.producer.messageType.impl.TransactionListenerImpl;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.*;

/**
 * 事务消息-生产者
 *
 * @author Roker
 * @date 2025/07/08
 */
public class TransactionMsgProducer {
    public static void main(String[] args) throws Exception {
        // 0、创建回查本地事务状态线程池
        ExecutorService executorService = new ThreadPoolExecutor(2, 5, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2000), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("client-transaction-msg-check-thread");
                return thread;
            }
        });
        // 1、实例化消息生产者，指定组名
        TransactionMQProducer producer = new TransactionMQProducer("roc_producer_group");
        // 2、设置NameServer的地址
        producer.setNamesrvAddr("127.0.0.1:9876");
        // 3、设置生产者回查线程池
        producer.setExecutorService(executorService);
        // 4、设置事务监听器，实现TransactionListener接口，实现executeLocalTransaction方法，
        // 返回COMMIT_MESSAGE、ROLLBACK_MESSAGE、UNKNOWN三种状态
        TransactionListener transactionListener = new TransactionListenerImpl();
        producer.setTransactionListener(transactionListener);
        producer.start();
        // 5、发送事务消息，设置回调函数来处理发送结果
        String[] tags = new String[] {"TagA", "TagB", "TagC", "TagD", "TagE"};
        for (int i = 0; i < 10; i++) {
            try {
                Message msg =
                        new Message("TOPIC_TRANSACTION", tags[i % tags.length], "KEY" + i,
                                ("事务消息测试- " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
//                msg.putUserProperty("CHECK_IMMUNITY_TIME_IN_SECONDS","10000");
                SendResult sendResult = producer.sendMessageInTransaction(msg, null);
                System.out.printf("%s%n", sendResult);

                Thread.sleep(10);
            } catch (MQClientException | UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        // 7、休眠10秒，保证消息消费完成，（等待事务检查回调）
        for (int i = 0; i < 100000; i++) {
            Thread.sleep(1000);
        }
        // 8、关闭生产者
        producer.shutdown();
    }
}